import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Room } from '../entities/room.entity';
import { HotelsService } from '../hotels/hotels.service';
import { CreateRoomInterface } from './interfaces/create-room.interface';

@Injectable()
export class RoomsService {
  private readonly mockRooms: CreateRoomInterface[] = [
    {
      roomType: '标准间',
      price: 299,
      status: '空闲',
      hotelID: 1,
    },
    {
      roomType: '豪华间',
      price: 599,
      status: '空闲',
      hotelID: 1,
    },
    {
      roomType: '总统套房',
      price: 1999,
      status: '空闲',
      hotelID: 1,
    },
    {
      roomType: '标准间',
      price: 359,
      status: '空闲',
      hotelID: 2,
    },
    {
      roomType: '豪华间',
      price: 699,
      status: '空闲',
      hotelID: 2,
    },
    {
      roomType: '标准间',
      price: 329,
      status: '空闲',
      hotelID: 3,
    },
  ];

  constructor(
    @InjectRepository(Room)
    private roomsRepository: Repository<Room>,
    private hotelsService: HotelsService,
  ) {
    // 初始化时添加模拟数据
    this.seedMockData();
  }

  private async seedMockData() {
    const count = await this.roomsRepository.count();
    if (count === 0) {
      await Promise.all(
        this.mockRooms.map((room) =>
          this.roomsRepository.save(this.roomsRepository.create(room)),
        ),
      );
    }
  }

  async findAll(): Promise<Room[]> {
    return this.roomsRepository.find({
      relations: ['hotel'],
    });
  }

  async findOne(id: number): Promise<Room> {
    const room = await this.roomsRepository.findOne({
      where: { roomID: id },
      relations: ['hotel'],
    });

    if (!room) {
      throw new NotFoundException(`未找到ID为${id}的房间`);
    }

    return room;
  }

  async findByHotel(hotelId: number): Promise<Room[]> {
    return this.roomsRepository.find({
      where: { hotelID: hotelId },
    });
  }

  async create(createRoomData: CreateRoomInterface): Promise<Room> {
    // 验证酒店是否存在
    await this.hotelsService.findOne(createRoomData.hotelID);

    const newRoom = this.roomsRepository.create(createRoomData);
    await this.roomsRepository.save(newRoom);
    return newRoom;
  }

  async update(id: number, updateData: Partial<Room>): Promise<Room> {
    const room = await this.findOne(id);

    // 如果更新了酒店ID，验证新酒店是否存在
    if (updateData.hotelID && updateData.hotelID !== room.hotelID) {
      await this.hotelsService.findOne(updateData.hotelID);
    }

    Object.assign(room, updateData);
    return this.roomsRepository.save(room);
  }

  async remove(id: number): Promise<void> {
    const result = await this.roomsRepository.delete(id);

    if (result.affected === 0) {
      throw new NotFoundException(`未找到ID为${id}的房间`);
    }
  }
}
